import random

from django.urls import reverse
from io import BytesIO
from time import sleep

# from django.core.cache import cache
from PIL import Image, ImageFont
from PIL.ImageDraw import Draw, ImageDraw
from django.core.cache import caches
from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.views.decorators.cache import cache_page

# 使用装饰器的方式调用缓存
# 制定缓存类型
from DjangoCache.models import Student_Cache
from HelloDjango import settings
from utils.utils import generate_code, get_color


@cache_page(60, cache='default')
def news(request):
    news_list = []

    for i in range(10):
        news_list.append("新闻%d" % i)
    sleep(5)
    data = {
        'news_list': news_list
    }

    return render(request, 'newlist.html', context=data)


# 不使用装饰器的方式调用缓存
def news_other(request):
    # 制定缓存类型
    cache = caches['redis_backend']
    # 获取缓存
    result = cache.get("news")
    # 如果有缓存，展现缓存内容
    if result:
        return HttpResponse(result)

    # 如果没有缓存，则进行下面操作，设置缓存
    news_list = []

    for i in range(10):
        news_list.append("新闻%d" % i)
    sleep(5)
    data = {
        'news_list': news_list
    }

    response = render(request, 'newlist.html', context=data)
    # 设置缓存
    cache.set("news", response.content, timeout=60)

    return response


def home(request):
    return HttpResponse("HOME")


def get_phone(request):
    if random.randrange(100) > 95:
        return HttpResponse("恭喜你！")

    return HttpResponse("排队中...")


def get_ticket(request):
    if random.randrange(100) > 10:
        return HttpResponse("还剩余99张")

    return HttpResponse("没有抢到")


def search(request):
    return HttpResponse("这是你搜索到的种子资源")


def calc(request):
    a = 250
    b = 250

    result = (a + b) / 0
    print(result)

    return HttpResponse("计算完成,结果：%d" % result)


def add_student(request):
    for i in range(100):
        student = Student_Cache()
        student.s_name = "小明%d" % i
        student.s_age = i
        student.save()

    return HttpResponse("学生创建成功")


# 原生实现分页
def get_student(request):
    # 页数，默认第一页
    page = int(request.GET.get("page", 1))
    # 每页项目数，默认10个
    per_page = int(request.GET.get("per_page", 10))
    # 制定数据的起止位置，起：per_page * (page - 1)，止：per_page
    students = Student_Cache.objects.all()[per_page * (page - 1):page * per_page]

    data = {
        "students": students
    }

    return render(request, 'students.html', context=data)


# 使用分页器
def get_students_with_page(request):
    # 页数，默认第一页
    page = int(request.GET.get("page", 1))
    # 每页项目数，默认10个
    per_page = int(request.GET.get("per_page", 10))

    students = Student_Cache.objects.all()
    # 获取学生列表的paginator对象，并指定每页多少数据
    paginator = Paginator(students, per_page)
    # 指定某一页
    page_object = paginator.page(page)

    data = {
        "page_object": page_object,
        "page_range": paginator.page_range
    }

    return render(request, 'students_with_paginator.html', context=data)


def get_code(request):
    mode = "RGB"
    size = (200, 100)
    color_bg = (255, 0, 0)

    # 先初始化画布
    image = Image.new(mode=mode, size=size, color=color_bg)
    # 再初始化画笔,需要传入画布
    imagedraw = ImageDraw(image, mode=mode)

    imagefont = ImageFont.truetype(font=settings.FONT_PATH, size=100)

    verify_code = generate_code()

    # 将verify_code存入session中用于验证正确性
    request.session['verify_code'] = verify_code

    for i in range(4):
        fill = (get_color(), get_color(), get_color())
        # 开始画text,一个字符一个字符地画，取4次，每次间隔50,填充色fill的三原色也是随机的
        imagedraw.text(xy=(50 * i, 0), text=verify_code[i], font=imagefont, fill=fill)

    for i in range(5000):
        # 画1000个点，颜色随机，坐标在 200*100 的画布中间
        fill = (get_color(), get_color(), get_color())
        xy = (random.randrange(201), random.randrange(100))
        imagedraw.point(xy=xy, fill=fill)

    # 创建一个内存流，打算将生成的图片放到内存流中，用过即删除
    fp = BytesIO()
    # 将图片保存至内存流
    image.save(fp, "png")
    # 将内存流传给浏览器，并告诉浏览器文件是一个PNG图片以供解析
    return HttpResponse(fp.getvalue(), content_type="image/png")


# 带验证码的登录
def login_with_verify_code(request):
    if request.method == 'GET':
        return render(request, 'login_with_verify_code.html')
    if request.method == 'POST':
        # 页面中输入的码
        receive_code = request.POST.get("verify_code")
        # session中的码
        store_code = request.session.get("verify_code")

        if receive_code.lower() != store_code.lower():
            return redirect(reverse('DjangoCache:login_with_verify_code'))

        return HttpResponse("登录成功")
